package com.bss.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.andy.basics.Constants;
import com.andy.basics.Dao;
import com.bss.dao.RoomDao;
import com.bss.model.Admission;
import com.bss.model.Room;
import com.bss.model.RoomBooking;

@Service
@Scope("session")
public class RoomService extends com.andy.basics.Service<Room> {

	private static final String CLASS = RoomService.class.getName();

	private static final Logger LOGGER = Logger.getLogger(Constants.TRACE_KEY + RoomService.CLASS);

	@Autowired
	protected RoomDao roomDao;

	public RoomService() {
		RoomService.LOGGER.info(RoomService.class.getName() + " initialized...");
	}

	@Override
	public Dao<Room> getDao() {
		return this.roomDao;
	}

	public void setBuildingDao(final RoomDao roomDao) {
		this.roomDao = roomDao;
	}

	public Admission findAdmission(Room room) {
		for (RoomBooking roomBooking : room.getRoomBookings()) {
			if (roomBooking.getRoom().getId().equals(room.getId())) {
				RoomService.LOGGER.debug("Admission found for " + room.getId() + ", Admission ID: "
						+ roomBooking.getAdmission().getId());
				return roomBooking.getAdmission();
			}
		}
		RoomService.LOGGER.debug("Admission NOT found for " + room.getId());
		return null;
	}

	public List<Room> findRooms(List<Room> rooms, final String condition) throws Exception {

		try {
			String[] conditions = condition.split(",");

			int total = rooms.size();

			for (int i = 0; i < total; i++) {
				Room room = rooms.get(i);
				for (String conditionVar : conditions) {
					String[] conditionVars = conditionVar.split("=");
					String attributeName = conditionVars[0];
					String valueExpected = conditionVars[1];
					Object valueActual = this.getUtils().getAttribute(room, attributeName);

					if ((valueActual != null) && !valueActual.toString().equals(valueExpected)) {
						rooms.remove(i);
						total = total - 1;
						i = i - 1;
						break;
					}
				}
			}
			return rooms;
		} catch (Exception e) {
			RoomService.LOGGER.error("Exception in findRooms(): " + e.getMessage(), e);
		}
		return null;
	}

	public List<Room> findDormitories(String buildingName) {
		return this.roomDao.find("building.name='" + buildingName + "' and dormitory = true");
	}

	public List<Room> findDormitories(List<Room> findRooms, String condition) throws Exception {
		return this.findRooms(findRooms, condition);
	}
}
